<?

abstract class bf_htmail {

	protected $log;

	public function __construct($options = array()) {

		$this->opts = array_merge(array(
			'host' => 'localhost',
			'port' => 25,
			'localhost' => null, // string or null (null means autodetect)
			'login' => false,
			'password' => false,
			'from' => 'robot@localhost',
			'from-name' => 'Robot',
			'buffer-limit' => 515,
			'timeout' => 3,
			'logging' => 1,
			'subject' => 'has no subject...',
			'log' => dirname(__FILE__) . '/../../../logs/htmail.log',
		), $options);

		$this->log = new bf_log($this->opts['log']);
	}

	abstract protected function sendmail($to, $headers, $body);

	public function send(
		$recepient, $subject, $body,
		$attachments = false,
		$is_html = true,
		$input_charset = 'UTF-8',
		$output_charset = 'UTF-8'
	) {
		$nl = "\r\n";

		$content_type = ($is_html ? 'text/html' : 'text/plain');

		$preferances = array(
			'scheme' => 'B',
			'input-charset' => $input_charset,
			'output-charset' => $output_charset
		);

		$body = chunk_split(base64_encode($body));

		$headers = "MIME-Version: 1.0\r\n";
		$headers .= iconv_mime_encode('From', $this->opts['from-name'], $preferances) . " <{$this->opts['from']}>{$nl}";
		$headers .= "To: <{$recepient}>\r\n";
		$headers .= "Date: ".date('r')."\r\n";
		$headers .= iconv_mime_encode('Subject', $subject, $preferances)."\r\n";

		if ($attachments !== false) {
			$un = strtoupper(uniqid(time()));
			$headers .= "Content-Type: multipart/mixed; boundary=\"----------$un\"\r\n";

			$body = "------------$un\r\nContent-Type: $content_type; charset=\"$output_charset\"\r\n"
				. "Content-Transfer-Encoding: base64\r\n"
				. "\r\n\r\n"
				. $body
			;

			foreach ($attachments as $filename) {
				if (!is_file($filename))
					continue;
				$body .= "------------$un\r\n";
				$body .= "Content-Type: application/octet-stream; ";
				$body .= "name=\"".basename($filename)."\"\r\n";
				$body .= "Content-Transfer-Encoding: base64\r\n";
				$body .= "Content-Disposition: attachment; ";
				$body .= "filename=\"".basename($filename)."\"\r\n\r\n";
				$body .= chunk_split(base64_encode(file_get_contents($filename)))."\n";
			}

		} else {
			$headers .= "Content-Type: $content_type; charset=\"$output_charset\"\r\n";
			$headers .= "Content-Transfer-Encoding: base64\r\n";
		}

		return $this->sendmail($recepient, $headers, $body);
	}
}

?>